Webページ上にテーブルデータを表示してキーワード検索するつまり
JavaScriptを使ってWebページの表示内容をユーザーの操作に応じて動的に変化させるようにしたい
まずはJavaScriptの実行環境の設定方法から…
1)Node.jsのインストール
Node.jsというプログラムをインストールするため、Node.jsのホームページに行き、推奨版をダウンロード
ファイルを実行してインストーラを起動
インストール中の設定はデフォルトのままでOK
Node.jsのインストールの完了
動作確認のためコマンドプロンプトを起動します
node --versionと入力し、バージョン情報が表示されていたらインストール成功です
2)VSCodeのインストール
VSCodeというプログラムをインストールするため、VSCodeのホームページに行き、Download nowをクリック
自身の環境に適したインストーラを選択しクリック
VSCodeもインストール中の設定はデフォルトのままでOK
インストールが完了したらVSCodeを起動し、日本語の言語パックをインストール
VSCodeの作業ホルダーの設定
デスクトップ上に作業ホルダ「work」を作成し、それをVSCodeにドラッグ&ドロップ
拡張機能
拡張機能アイコンをクリック
「live server」という拡張機能を検索します
インストールをクリックし、Live Serverをインストール
ここまでで環境設定は完了
【確認作業】
作業ホルダをクリックして、作業ホルダに戻る
拡張機能のタブを閉じる
作業ホルダの下で右クリックして「新しいファイル」を選択し、名前は「index.html」とします
ファイルの編集画面が表示される
「!」を入力してからTabキーを押すと、htmlのテンプレートが生成される
htmlファイルを右クリックして「Open with Live Server」を選択する
するとブラウザが立ち上がります
自身のローカルPC上(127.0.0.1)にWEBサーバーが起動され、index.htmlが表示される
Hello world!とhtmlを書き換え、「Ctrl」+「S」で変更を保存して、ブラウザに戻る
変更が反映されたか確認します
3)HTML/JavaScriptの実装
~テーブルデータの表示・検索機能~
作業ホルダ「work」にcsvファイルを格納する
VSCode上に表示される
index.htmlをコピーして、新しいhtmlファイルを作成
ファイル名を「example.html」とする。
HTMLは、検索ボックスで文字列を受け取る、JavaScriptを実行するの2つの処理を行います。
HTMLコードは次のとおり。
□□□□example.htmlのHTMLコードは次のとおり□□□□
example
example
example.jsのファイルを作成します。example.jsは、CSVファイルの読込、HTMLのテーブルに変換、レコード検索機能の3つの処理を行います
□□□□example.jslのコードは次のとおり□□□□
// レコード検索処理
window.addEventListener( "DOMContentLoaded",
function(){
const search = document.forms[ 0 ].search;
const table = document.querySelector( "table" );
const nohit = table.parentNode.insertBefore(document.createElement( "div" ), table.nextNode);
nohit.textContent = "該当なし";
nohit.style.display = "none";
search.oninput = function(){
const key = search.value.replace( /([\\\*\+\.\?\{\}\(\)\[\]\^\$\-\|\/])/g, "\\$1" );
let hit = 0;
[].forEach.call( table.rows,
function( row, index ){
if( index==0 ){ return false }
row.style.display = [].some.call( row.cells,
function( cell ){
return ( new RegExp( key ) ).test( cell.textContent );
}
) ? "table-row" : "none" ;
row.style.display=="table-row" ? hit++ : hit ;
}
);
nohit.style.display = hit ? "none" : "block" ;
}
},
false
);
const outputElement = document.getElementById('data_csv');
// CSVデータの読み込み
function getCsvData(dataPath) {
const request = new XMLHttpRequest();
request.addEventListener('load',
(event) => {
const response = event.target.responseText;
convertArray(response);
}
);
request.open('GET', dataPath, true);
request.send();
}
// CSVデータをHTMLのテーブル形式に変換
function convertArray(data) {
const dataArray = [];
const dataString = data.split('\n');
for (let i = 0; i < dataString.length; i++) {
dataArray[i] = dataString[i].split(',');
}
let insertElement = '';
dataArray.forEach(
(element) => { insertElement += '';
element.forEach(
(childElement) => { insertElement += `${childElement} | ` }
);
insertElement += '
';
}
);
outputElement.innerHTML = insertElement;
}
【確認作業】
visual Studio Code からexample.htmlを「Open with Live Server」で起動し、ブラウザにCSVファイルが反映されているか確認する
文字列を検索して表示が変化するのを確認する